package com.shuqi.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.shuqi.activity.adapter.MyFavoritAdapter;
import com.shuqi.activity.viewport.MyFavoritTitle;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.DialogUtils;
import com.shuqi.common.utils.ToastUtil;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.MainController;
import com.shuqi.controller.MyFavoritController;
import com.shuqi.controller.MyFavoritController.ActionEnum;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.MyFavoritBean;
import com.shuqi.model.bean.MyFavoritBean.MyFavorityItemBean;
import com.shuqi.model.bean.MyFavoritRemoveBean;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 
 * 我的收藏
 * 
 * @author li.li
 * @date 2014-06-11
 */
public class MyFavoritActivity extends ActivityBase implements OnClickListener,
        OnItemLongClickListener, OnItemClickListener, IEventListener, OnScrollListener {

    private MyFavoritTitle mTitle;// 标题
    // private List<MyFavoritBean> myFavorits;// 收藏的书
    private MyFavoritAdapter adapter;
    private LinearLayout actMyFavoritNull; // 无浏览书籍
    private TextView actMyFavoritGoshucheng;// 去书城
    private ListView myFavoritlv;// 收藏书列表

    private TextView myFavoritTopTV;
    private LinearLayout myFavoritTopBanner;

    private static final int init = EventTypeConstants.BASE;
    private static final int init_success = init + 1;
    private static final int init_error = init_success + 1;
    private static final int loadmore_error = init_error + 1;
    public static final int my_favorit_remove = loadmore_error + 1;
    public static final int NEED_LOGIN = my_favorit_remove + 1;

    private MyFavoritController controller;
    private LinearLayout layoutLoading;// 网络加载
    private View netError;// 网络错误

    private ToastDialog toastDialog;
    private Dialog mDelDialog;

    private int position;// 当前位置

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case init:
                    activityLogicForward();
                    break;
                case init_success:
                    if (msg.arg1 == 1) {// 收藏列表结果处理
                        activityInitData();
                    } else if (msg.arg1 == 2) {// 取消收藏结果处理
                        myFavoritlv.setVisibility(View.VISIBLE);
                        // layoutLoading.setVisibility(View.GONE);
                        netError.setVisibility(View.GONE);
                        dismissDialog();

                        adapter.remove();// 删除本地
                        setMyFavoritTop();

                        if (adapter.getList() == null || adapter.getList().isEmpty()) {
                            actMyFavoritNull.setVisibility(View.VISIBLE);
                            myFavoritlv.setVisibility(View.GONE);
                            mTitle.setStyle(true, false);

                            // 没有结果退出编辑状态
                            unEditable();
                        }

                        String message = msg.getData().getString("message");
                        ToastUtil.showMessage(message);
                    }

                    break;
                case init_error:
                    dismissDialog();
                    layoutLoading.setVisibility(View.GONE);
                    netError.setVisibility(View.VISIBLE);
                    myFavoritlv.setVisibility(View.GONE);
                    setMyFavoritTop();
                    break;
                case loadmore_error:
                    dismissDialog();
                    layoutLoading.setVisibility(View.GONE);
                    showMsg("网络异常");
                    break;
                case my_favorit_remove:// 执行取消收藏请求
                    // layoutLoading.setVisibility(View.VISIBLE);
                    showDialog("移除中，请稍候...");
                    String bookId = msg.getData().getString("bookId");
                    controller.handle(0, ActionEnum.remove, bookId);
                    break;
                case NEED_LOGIN:// 跳登陆界面
                    dismissDialog();
                    LoginActivity.openVerifyForResult(MyFavoritActivity.this, -1);
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_my_favorit);

        this.controller =
                (MyFavoritController) MainController.getMainManagerInstance().createController(
                        MainController.CONTROLLER_ID_MY_FAVORIT, this);
        this.controller.addEventListener(this);
        
    }

    @Override
    protected void onResume() {
        super.onResume();

        handler.sendEmptyMessage(init);
    }

    @Override
    public void activityLogicForward() {
        adapter = new MyFavoritAdapter(getApplicationContext(), handler);

        layoutLoading = (LinearLayout) findViewById(R.id.include_loading);
        netError = (LinearLayout) findViewById(R.id.include_error);

        mTitle = (MyFavoritTitle) findViewById(R.id.title);
        mTitle.setImageListener(this);
        mTitle.setStyle(true, false);

        myFavoritTopTV = (TextView) findViewById(R.id.act_my_favorit_top_text);
        myFavoritTopBanner = (LinearLayout) findViewById(R.id.act_my_favorit_top_banner);

        myFavoritlv = (ListView) findViewById(R.id.my_favorit_lv);
        actMyFavoritNull = (LinearLayout) findViewById(R.id.act_my_favorit_null);
        actMyFavoritGoshucheng = (TextView) findViewById(R.id.act_my_favorit_goshucheng);

        actMyFavoritGoshucheng.setOnClickListener(this);
        myFavoritlv.setOnItemClickListener(this);// 处理listview长按
        myFavoritlv.setOnItemLongClickListener(this);// 处理listview单击
        myFavoritlv.setOnItemLongClickListener(this);
        myFavoritlv.setOnScrollListener(this);
        findViewById(R.id.retry).setOnClickListener(this);
        
      //修改listview默认的滑动条
        Util.setScrollBar(this,myFavoritlv,R.drawable.fast_bar_normal);

        // 请求数据，loading页面显示
        controller.handle(0, ActionEnum.getList);
        layoutLoading.setVisibility(View.VISIBLE);

        if (adapter.isCanEdit())
            unEditable();

    }

    @Override
    public void activityInitData() {
        myFavoritlv.setVisibility(View.VISIBLE);
        layoutLoading.setVisibility(View.GONE);
        netError.setVisibility(View.GONE);

        // 是否有收藏记录
        if (adapter.getList() != null && !adapter.getList().isEmpty()) {
            setMyFavoritTop();

            adapter.setData(adapter.getList());
            myFavoritlv.setAdapter(adapter);
            mTitle.setStyle(true, true);

            if (adapter.isCanEdit()) {
                editable();
            } else {
                unEditable();
            }

        } else {
            myFavoritTopBanner.setVisibility(View.GONE);
            actMyFavoritNull.setVisibility(View.VISIBLE);
            myFavoritlv.setVisibility(View.GONE);
            mTitle.setStyle(true, false);

            // 没有结果退出编辑状态
            unEditable();

        }

        // 定位到上次位置
        myFavoritlv.setSelection(position);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;

            case R.id.title_right:
                switchEdit();
                break;

            case R.id.act_my_favorit_goshucheng:// 去书城
                MainActivityGroup.show(this, MainActivityGroup.PAGE_POSITION_BOOKSQUARE, true);
                break;

            case R.id.retry:
                // if (!Util.isNetworkConnected(this)) {
                // return;
                // } else {
                // controller.handle(0, ActionEnum.getList);
                // layoutLoading.setVisibility(View.VISIBLE);
                // }
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        controller.handle(0, ActionEnum.getList);
                        layoutLoading.setVisibility(View.VISIBLE);

                    }
                });
                break;


            default:
                break;
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MyFavorityItemBean myFavorityItemBean = adapter.getList().get(position);

        if (MyFavoritBean.COVER_OPEN.equals(myFavorityItemBean.getCrCoverIsopen())
                && MyFavoritBean.BOOK_OPEN.equals(myFavorityItemBean.getHide())) {

            BookCoverActivity.openBookCover(this, myFavorityItemBean.getBookId());

        } else { // 跳到书城推荐

            Intent intent = new Intent(this, BookSearchResultActivity.class);
            intent.putExtra("keyword", myFavorityItemBean.getBookName());
            ActivityManager.getInstance().startNextActivity(intent, this);

        }
        StatisticsUtils.onEvent(this, StatisticsEventID.MYCOLLECTION_SHOW);
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        MyFavorityItemBean myFavorityItemBean = adapter.getList().get(position);
        showBottomDelDialog(myFavorityItemBean, position);

        return true;
    }

    @Override
    public void onEvent(int event, Object data) {// 处理异步返回结果


        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:

                if (data instanceof MyFavoritBean) {// 收藏列表
                    MyFavoritBean myFavoritBean = (MyFavoritBean) data;

                    if ("304".equals(myFavoritBean.getState())) {// 需要登陆
                        Message msg = Message.obtain();
                        msg.what = NEED_LOGIN;
                        Bundle bundle = new Bundle();
                        bundle.putString("message", myFavoritBean.getMessage());
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                        return;
                    }

                    if (adapter.getList() == null) {
                        adapter.setData(myFavoritBean.getItemList());
                    } else {
                        adapter.setData(myFavoritBean.getItemList());
                        adapter.getList().addAll(myFavoritBean.getItemList());
                    }
                    Message msg = Message.obtain();
                    msg.what = init_success;
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                } else if (data instanceof MyFavoritRemoveBean) {// 取消收藏
                    MyFavoritRemoveBean myFavoritRemoveBean = (MyFavoritRemoveBean) data;

                    if ("304".equals(myFavoritRemoveBean.getState())) {// 需要登陆
                        Message msg = Message.obtain();
                        msg.what = NEED_LOGIN;
                        Bundle bundle = new Bundle();
                        bundle.putString("message", myFavoritRemoveBean.getMessage());
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                        return;
                    }

                    Message msg = Message.obtain();
                    msg.what = init_success;
                    msg.arg1 = 2;
                    Bundle bundle = new Bundle();
                    bundle.putString("message", myFavoritRemoveBean.getMessage());
                    msg.setData(bundle);
                    handler.sendMessage(msg);
                }

                break;
            default:
                if (adapter.getList() == null) {
                    handler.sendEmptyMessage(init_error);
                } else {
                    handler.sendEmptyMessage(loadmore_error);
                }
                break;
        }

    }

    private void setMyFavoritTop() {

        if (adapter.getList() != null && !adapter.getList().isEmpty()) {
            myFavoritTopBanner.setVisibility(View.VISIBLE);
            String popMsg = "共收藏<font color=\"#479af8\">" + adapter.getList().size() + "本</font>书";
            myFavoritTopTV.setText(Html.fromHtml(popMsg));

        } else {
            myFavoritTopBanner.setVisibility(View.GONE);

        }
    }

    private void showDialog(String msg) {

        if (toastDialog == null) {
            toastDialog = new ToastDialog(this);
            toastDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {}
            });
        }
        toastDialog.setDissmisOnClickOutSide(false);
        toastDialog.loading(msg);
    }

    private void dismissDialog() {
        if (toastDialog != null) {
            toastDialog.dismiss();
        }

    }

    // 显示删除的dialog
    private void showBottomDelDialog(final MyFavorityItemBean myFavoritItemBean, final int position) {

        if (myFavoritItemBean == null) {
            return;
        }

        String title = myFavoritItemBean.getBookName();
        String content = "确定删除所选的书籍吗？";

        if (mDelDialog != null && !mDelDialog.isShowing()) {
            mDelDialog.dismiss();
        }

        mDelDialog =
                DialogUtils.showDialogConfirmBottom(this, title, content, "确定", "取消",
                        new OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                DialogUtils.dismissDialog(mDelDialog);
                                // 执行删除书
                                adapter.delFavoritBook(myFavoritItemBean, position);

                            }
                        }, new OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                DialogUtils.dismissDialog(mDelDialog);

                            }
                        });


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (adapter.isCanEdit()) {
                switchEdit();
            } else {
                ActivityManager.getInstance().finishActivity(this);
            }


            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount) {


    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // 不滚动时保存当前滚动到的位置
        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            position = myFavoritlv.getFirstVisiblePosition();

        }

    }

    /**
     * 切换编辑状态和浏览状态
     */
    private void switchEdit() {

        if (adapter.isCanEdit()) {
            unEditable();
        } else {
            editable();
        }
    }

    /**
     * 设置可编辑
     */
    private void editable() {
        // 文字显示切换
        TextView rightTextView = mTitle.getRightTextView();
        String done = getString(R.string.my_favorit_top_right_done);
        adapter.setCanEdit(true);
        rightTextView.setText(done);
        mTitle.getLeftImageView().setVisibility(View.INVISIBLE);

        adapter.notifyDataSetChanged();
    }

    /**
     * 设置不可编辑
     */
    private void unEditable() {
        // 文字显示切换
        TextView rightTextView = mTitle.getRightTextView();
        String admin = getString(R.string.my_favorit_top_right_admin);
        adapter.setCanEdit(false);
        rightTextView.setText(admin);
        mTitle.getLeftImageView().setVisibility(View.VISIBLE);

        adapter.notifyDataSetChanged();

    }



}
